<template>
	<view class="">
		<view class='cell-group payment-method' style="border-radius: 20rpx;">
			<view class='cell-item add-title-item cell-item-mid right-img' v-for="item in payments" :key="item.code"
				@click="modelshow(item.code)" v-if="!(type == 2 && item.code == 'balancepay')">
				<view class='cell-item-hd'>
					<image class='cell-hd-icon' :src='item.icon'></image>
				</view>
				<view class='cell-item-bd cell-item-bd-block'>
					<view class="cell-bd-view">
						<text class="cell-bd-text">{{ item.name }}</text>
					</view>
					<view class="cell-bd-view">
						<text class="cell-bd-text address">{{ item.memo }}</text>
					</view>
				</view>
				<view class='cell-item-ft'>
					<image class='cell-ft-next icon' src='/static/image/right.png'></image>
				</view>
			</view>
		</view>
		<u-modal :show="ShowPoP" :show-cancel-button="true" @cancel="CancelSHow" @confirm="toPayHandler(ZC)"
			content="是否确认支付" title="确认支付" width="500rpx"></u-modal>
	</view>
</template>

<script>
	import {
		apiBaseUrl
	} from '@/config/config.js'
	const module = uni.requireNativePlugin('SandPayTypeModule')
	export default {
		props: {
			// 如果是商品订单此参数必须
			orderId: {
				type: String,
				default () {
					return ''
				}
			},
			// 如果是充值订单此参数必须
			recharge: {
				type: Number,
				default () {
					return 0
				}
			},
			// 用户id
			uid: {
				type: Number,
				default () {
					return 0
				}
			},
			// 订单类型
			type: {
				type: Number,
				default () {
					return 1
				}
			}
		},
		data() {
			return {
				payments: [],
				popShow: false,
				ShowPoP: false,
				ZC: ''
			}
		},
		mounted() {

			this.getPayments()
		},
		methods: {
			// 获取可用支付方式列表
			getPayments() {
				this.$api.paymentList({}, res => {
					if (res.status) {
						this.payments = this.formatPayments(res.data)
					}
				})
			},
			// 支付方式处理
			formatPayments(payments) {
				if (this.type === 1) {
					payments = payments.filter(
						item => item.code !== 'offline'
					)
				}
				// 如果是充值订单 过滤余额支付 过滤非线上支付方式
				if (this.type === 2) {
					payments = payments.filter(item => item.code !== 'balancepay' || item.is_online === 1)
				}

				// 设置logo图片
				payments.forEach(item => {
					this.$set(item, 'icon', '/static/image/' + item.code + '.png')
				})
				return payments
			},
			modelshow(e) {
				this.ZC = e
				this.ShowPoP = true
			},
			CancelSHow() {
				this.ShowPoP = false
			},
			// 用户点击支付方式处理
			toPayHandler(code) {
				// this.popShow = true;
				this.ShowPoP = false
				let _this = this

				let data = {
					payment_code: code,
					payment_type: _this.type
				}

				data['ids'] = (this.type == 1 || this.type == 5 || this.type == 6) ? this.orderId : this.uid
				if ((this.type == 5 || this.type == 6) && this.recharge) {
					data['params'] = {
						trade_type: 'APP',
						formid: this.orderId
					}
				}
				switch (code) {
					case 'sxypay':
						data['params'] = {
							trade_type: 'APP',
							money: _this.recharge,
							payerName: this.payerName,
							idType: this.idType,
							idNum: this.idNum,
							bankCardNum: this.bankCardNum,
							email: this.email,

						}
						_this.$api.pay(data, res => {
							if (res.status) {
								plus.runtime.openURL(res.data)
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							} else {
								_this.$common.errorToShow(res.msg)
							}
						})

						break
					case 'alipaywap':
						if (this.type == 1 && this.orderId) {
							data['params'] = {
								trade_type: 'WAP',
								return_url: baseUrl +
									'wapp/pages/goods/payment/result'
							}
						} else if (this.type == 2 && this.recharge) {
							data['params'] = {
								money: this.recharge,
								recharge_id: this.recharge_id,
								return_url: baseUrl + 'wapp/pages/goods/payment/result'
							}
						} else if ((this.type == 5 || this.type == 6) && this.recharge) {
							data['params'] = {
								formid: this.orderId
							}
						}

						this.$api.pay(data, res => {
							if (res.status) {
								const url = res.data.url
								const data = res.data.data
								console.log(res)
								plus.runtime.openURL(apiBaseUrl + 'b2c/index/alipaywap?' + data)

							} else {
								this.$common.errorToShow(res.msg)
							}
						})
						break
					case 'alipay':
						if (_this.type == 1 && _this.orderId) {
							data['params'] = {
								trade_type: 'APP'
							}
						} else if (_this.type == 2 && _this.recharge) {
							data['params'] = {
								trade_type: 'APP',
								money: _this.recharge
							}
						}

						_this.$api.pay(data, res => {
							if (res.status) {
								uni.requestPayment({
									provider: "alipay",
									orderInfo: res.data.data,
									success: function(data) {
										_this.$common.successToShow('支付成功', () => {
											_this.redirectHandler(res.data.payment_id)
										})
									}
								});
							} else {
								_this.$comon.errorToShow(res.msg)
							}
						})
						break
					case 'alipayds':
						if (_this.type == 1 && _this.orderId) {
							data['params'] = {
								trade_type: 'APP'
							}
						} else if (_this.type == 2 && _this.recharge) {
							data['params'] = {
								trade_type: 'APP',
								money: _this.recharge
							}
						}

						_this.$api.pay(data, res => {
							if (res.status) {
								uni.requestPayment({
									provider: "alipay",
									orderInfo: res.data.data,
									success: function(data) {
										_this.$common.successToShow('支付成功', () => {
											_this.redirectHandler(res.data.payment_id)
										})
									}
								});
							} else {
								_this.$comon.errorToShow(res.msg)
							}
						})
						break
					case 'alipayhh':
						if (_this.type == 1 && _this.orderId) {
							data['params'] = {
								trade_type: 'APP'
							}
						} else if (_this.type == 2 && _this.recharge) {
							data['params'] = {
								trade_type: 'APP',
								money: _this.recharge
							}
						}

						_this.$api.pay(data, res => {
							if (res.status) {
								uni.requestPayment({
									provider: "alipay",
									orderInfo: res.data.data,
									success: function(data) {
										_this.$common.successToShow('支付成功', () => {
											_this.redirectHandler(res.data.payment_id)
										})
									}
								});
							} else {
								_this.$comon.errorToShow(res.msg)
							}
						})
						break
					case 'alipayhhg':
						if (_this.type == 1 && _this.orderId) {
							data['params'] = {
								trade_type: 'APP'
							}
						} else if (_this.type == 2 && _this.recharge) {
							data['params'] = {
								trade_type: 'APP',
								money: _this.recharge
							}
						}

						_this.$api.pay(data, res => {
							if (res.status) {
								uni.requestPayment({
									provider: "alipay",
									orderInfo: res.data.data,
									success: function(data) {
										_this.$common.successToShow('支付成功', () => {
											_this.redirectHandler(res.data.payment_id)
										})
									}
								});
							} else {
								_this.$comon.errorToShow(res.msg)
							}
						})
						break
					case 'wechatpay':
					case 'wechatpayhh':
					case 'wechatpayds':
						// 微信 H5支付
						if (_this.type == 1 && _this.orderId) {
							data['params'] = {
								trade_type: 'APP'
							}
						} else if (_this.type == 2 && _this.recharge) {
							data['params'] = {
								trade_type: 'APP',
								money: _this.recharge
							}
						}

						// 微信app支付
						_this.$api.pay(data, res => {
							if (res.status) {
								//console.log(JSON.stringify(res));
								// 调用微信支付  
								uni.requestPayment({
									provider: "wxpay",
									orderInfo: {
										appid: res.data.appid,
										noncestr: res.data.noncestr,
										package: res.data.package,
										partnerid: res.data.partnerid,
										prepayid: res.data.prepayid,
										timestamp: res.data.timestamp,
										sign: res.data.sign,
									},
									success: function(data) {
										_this.$common.successToShow('支付成功', () => {
											_this.redirectHandler(res.data.payment_id)
										})
									},
									fail: function(res) {
										console.log(JSON.stringify(res));
									}
								});
							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break
					case 'balancepay':
						/**
						 *  用户余额支付
						 * 
						 */
						_this.$api.pay(data, res => {
							if (res.status) {
								_this.redirectHandler(res.data.payment_id, this.orderId)
							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break
					case 'offline':
						/**
						 * 线下支付
						 */
						_this.$common.modelShow('线下支付说明', '请联系客服进行线下支付', () => {}, false, '取消', '确定')
						break
					case 'shandepay':
						data['params'] = {
							trade_type: 'bank',
						}
						_this.$api.pay(data, res => {
							if (res.status) {
								plus.runtime.openURL(res.data)
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break

					case 'sandwechatpay':
						if (_this.type == 1 && _this.orderId) {
							data['params'] = {
								trade_type: 'APP'
							}
						} else if (_this.type == 2 && _this.recharge) {
							data['params'] = {
								trade_type: 'APP',
								money: _this.recharge
							}
						}
						_this.$api.pay(data, res => {
							if (res.status) {
								module.cashierPaySingle(res.data, ret => {
									if (ret.payType == '1') {
										this.wxPay(ret.tokenId)
									} else {
										this.endLoading()
										if (ret.resultCode == '0000') {
											console.log("支付方式:" + ret.payType)
										}
										console.log("支付结果:" + ret.resultCode)
										console.log("错误信息:" + ret.failReason)
										console.log("action:" + ret.action)
									}
								})
							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break
					case 'adawechatpay':
						data['params'] = {
							trade_type: 'APP'
						}
						plus.share.getServices(shareList => {
							let sweixin = shareList.find(val => val.id == 'weixin')
							if (sweixin) {


								sweixin.launchMiniProgram({
									id: 'gh_b25107cbd606', //小程序原始idmoney: _this.recharge
									path: 'pages/adapay/index?payment_type=' + data.payment_type +
										'&token=' + _this.$db.get('userToken') + '&ids=' + data.ids,
									type: 0
								})
								this.endLoading()
							} else {
								uni.showToast({
									icon: 'none',
									title: "未安装微信,无法打开对应小程序"
								})
							}
						}, e => {
							uni.showToast({
								icon: 'none',
								title: "获取微信服务列表失败:" + JSON.stringify(e)
							})
						})
						break
					case 'sandalipayqr':
						data['params'] = {
							trade_type: 'alipay',
							money: _this.recharge
						}
						_this.$api.pay(data, res => {

							if (res.status) {
								plus.runtime.openURL(res.data)

							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break
					case 'sandjuhe':
						data['params'] = {
							money: _this.recharge
						}
						_this.$api.pay(data, res => {
							// return;

							if (res.status) {


								this.$common.navigateTo('/pages/webview/yunshanfu?url=' + res.data)

							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break

					case 'uijuhepay':
						var transitUrl = '';
						transitUrl =
							apiBaseUrl +
							'wapp/pages/goods/payment/auth?recharge=' +
							_this.recharge +
							'&type=' +
							_this.type;
						data['params'] = {
							money: _this.recharge,
							frontUrl: transitUrl
						}
						_this.$api.pay(data, res => {

							if (res.status) {

								plus.runtime.openURL(
									'alipays://platformapi/startapp?appId=20000067&url=' + res
									.data, //这里的appId=20000067是固定的，不需要改
									res => {
										//这里写打开URL地址失败后的处理
										uni.showModal({
											content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
											success: function(res) {
												if (res.confirm) {
													//plus.runtime.openURL();
												}
											}
										});
									},
									'com.eg.android.AlipayGphone'
								);

							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break

					case 'uiwxpay':
						var transitUrl =
							apiBaseUrl +
							'wapp/pages/goods/payment/auth?recharge=' +
							_this.recharge +
							'&type=' +
							_this.type;

						data['params'] = {
							money: _this.recharge,
							frontUrl: transitUrl,
							payDataType: 'codeImgUrl'
						}
						_this.$api.pay(data, res => {
							if (res.status) {

								this.$common.navigateTo('/pages/webview/image?url=' + res.data)


							} else {
								_this.$common.errorToShow(res.msg)
							}
						})
						break
					case 'xfpayyxd':
						data['params'] = {
							trade_type: 'APP',
							money: _this.recharge
						}
						_this.$api.pay(data, res => {
							if (res.status) {
								this.$common.navigateTo('/pages/webview/yunshanfu?url=' + res.data)
							} else {
								_this.$common.errorToShow(res.msg)
							}
						})

						break
					case 'sxypay':
						data['params'] = {
							trade_type: 'APP',
							money: _this.recharge,
							payerName: this.payerName,
							idType: this.idType,
							idNum: this.idNum,
							bankCardNum: this.bankCardNum,
							email: this.email,

						}
						_this.$api.pay(data, res => {
							if (res.status) {
								plus.runtime.openURL(res.data)
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							} else {
								_this.$common.errorToShow(res.msg)
							}
						})

						break
					default:
						uni.showToast({
							icon: 'none',
							title: "版本过低 ，请重新下载"
						})
						break

				}
			},
			wxPay(tokenId) {

				plus.share.getServices(shareList => {
					let sweixin = shareList.find(val => val.id == 'weixin')
					if (sweixin) {
						this.connectSocket();
						sweixin.launchMiniProgram({
							id: 'gh_b25107cbd606', //小程序原始id
							path: 'pages/zf/index?token_id=' + tokenId,
							type: 0
						})
						this.endLoading()
					} else {
						uni.showToast({
							icon: 'none',
							title: "未安装微信,无法打开对应小程序"
						})
					}
				}, e => {
					uni.showToast({
						icon: 'none',
						title: "获取微信服务列表失败:" + JSON.stringify(e)
					})
				})

			},
			startLoading(message) {
				uni.showLoading({
					title: message
				})
			},
			endLoading() {
				uni.hideLoading()
			},
			// 支付成功后跳转操作
			redirectHandler(paymentId) {
				let that = this
				this.$common.redirectTo('/pages/goods/payment/result?id=' + paymentId + '&oid=' + that.orderId)
			},
			// 支付中显示隐藏
			popBtn() {
				this.popShow = false
			},
			// 开启socket
			connectSocket() {
				let that = this;
				uni.connectSocket({
					url: 'ws://47.92.193.240:30001'
				});
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开！');
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
				});
				uni.onSocketMessage(function(res) {
					that.getSocketMessage(res);
				});
				uni.onSocketClose(function(res) {
					console.log('WebSocket 已关闭！');
				});
			},

			// 关闭socket
			closeSocket() {
				uni.closeSocket()
			},
			// 发送消息
			sendSocketMessage(msg) {
				console.log(msg);
				msg = JSON.stringify(msg)
				uni.sendSocketMessage({
					data: msg
				});
			},
			// 接收消息
			getSocketMessage(msg) {
				console.log(msg);
				let data = JSON.parse(msg.data)
				switch (data.method) {
					case "payment":
						if (data.status) {
							this.$common.successToShow('支付成功', () => {
								this.redirectHandler(data.payment_id)
							})
						} else {
							_this.$common.errorToShow('支付失败')
						}
						break;
					default:
						console.log(data);
						break;
				}
			}
		},
		onHide() {
			console.log('11111')
			this.closeSocket();
		},
		onUnload() {
			console.log('asdasdasd')
			this.closeSocket();
		},

	}
</script>

<style>
	.cell-item {
		padding: 20rpx 30rpx;
		background-color: transparent;
	}

	.payment-method .cell-item-hd {
		min-width: 70upx;
	}

	.payment-method .cell-hd-icon {
		width: 70upx;
		height: 70upx;
	}

	.payment-method .cell-item-bd {
		border-left: 2upx solid #F0F0F0;
		padding-left: 30upx;
	}

	.payment-method .cell-bd-text {
		font-size: 28upx;
		color: #666;
	}

	.payment-method .address {
		font-size: 24upx;
		color: #999;
	}

	.payment-pop {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 400rpx;
		height: 272rpx;
		background-color: #fff;
		text-align: center;
		box-shadow: 0 0 20rpx #ccc;
		/* border-radius: 10rpx; */
	}

	.payment-pop-c {
		padding: 50rpx 30rpx;
		/* line-height: 300rpx; */
		font-size: 32rpx;
		color: #999;
	}

	.payment-pop-b {
		position: absolute;
		bottom: 0;
		display: flex;
		width: 100%;
		justify-content: space-between;
	}

	.payment-pop-b .btn {
		flex: 1;
		justify-content: center;
	}

	.payment-pop .text {
		font-size: 24upx;
	}
</style>